# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import AccessError, UserError, ValidationError
import odoo.addons.decimal_precision as dp

class PriceListSaleOrder(models.Model):
    _inherit = 'sale.order'

    # 搜尋銷售明細的備註，待整合
    # search_remarks = fields.Char(related='order_line.remarks')
    search_partner_mobile = fields.Char(related='partner_id.mobile')
    search_partner_phone = fields.Char(related='partner_id.phone')
    key_in_user = fields.Many2one(comodel_name='res.users', string='製單人員', default=lambda self: self.env.uid, readonly=True)
    client_remarks = fields.Text(string='收貨備註')
    client_ref = fields.Char(string='客戶單號')
    show_product_image = fields.Boolean(string='列印產品圖片')

    @api.multi
    def action_confirm(self):
        res = super(PriceListSaleOrder, self).action_confirm()
        purchase_order_id = self.env['purchase.order'].search([('origin','=',self.name),('state','=','draft')],limit=1)
        if purchase_order_id:
            for line in purchase_order_id:
                line.client_remarks = self.client_remarks
                line.client_ref = self.client_ref

        # elif not purchase_order_id:
        #     raise ValidationError(u'錯誤，採購詢價單未建立')
        return res

    def action_unlock(self):
        self.state = 'sale'

    @api.multi
    @api.depends('procurement_group_id')
    def _compute_picking_ids(self):
        super(PriceListSaleOrder, self)._compute_picking_ids()
        stock_picking_id = self.env['stock.picking'].search([('origin','=',self.name)])
        if stock_picking_id:
            stock_picking_id.write({'client_remarks': self.client_remarks,'client_ref': self.client_ref})
            stock_picking_id.env.cr.commit()



    # @api.multi
    # def write(self, vals):
    #     res = super(PriceListSaleOrder, self).write(vals)
    #
    #     stock_picking_id = self.env['stock.picking'].search([('origin','=',self.name)],limit=1)
    #     if stock_picking_id:
    #         stock_picking_id.client_remarks = self.client_remarks
    #         stock_picking_id.client_ref = self.client_ref
    #     return res
    # 取消銷售訂單檢查發票出貨
    @api.multi
    def action_cancel(self):
        res = super(PriceListSaleOrder, self).action_cancel()
        if len(self.invoice_ids) > 0:
            for line in self.invoice_ids:
                if line.state not in ('cancel'):
                    raise ValidationError(u'錯誤，此銷售單還有發票未手動取消')

        if len(self.picking_ids) > 0:
            for line in self.picking_ids:
                if line.state in 'done':
                    raise ValidationError(u'錯誤!，此銷售單已經出貨，不能夠取消銷售訂單')
        return res

class PriceListSaleOrderLine(models.Model):
     _inherit = 'sale.order.line'

    # @api.multi
    # def _prepare_order_line_procurement(self, group_id=False):
    #     res = super(PriceListSaleOrderLine, self)._prepare_order_line_procurement(group_id=group_id)
    #     res.update({'price_unit': self.price_unit * self.discount})
    #     return res
    # @api.multi
    # def _prepare_order_line_procurement(self, group_id=False):
    #     res = super(PriceListSaleOrderLine, self)._prepare_order_line_procurement(group_id=False)
    #     res.update({'price_unit': self.yifeng_price_unit * self.discount})
    #     return res
    # @api.multi
    # def _prepare_order_line_procurement(self, group_id=False):
    #     res = super(PriceListSaleOrderLine, self)._prepare_order_line_procurement(group_id)
    #     res.update({'client_remarks': self.order_id.client_remarks})
     #    res.update({'client_ref': self.order_id.client_ref})

#
#     price_list = fields.Text(string='價格表')
#     group_lock = fields.Boolean(string='業務邏輯用變數')
#     yifeng_price_unit = fields.Float(string='單價', related='price_unit', readonly=True)
#     remarks = fields.Char(string='備註')
#
#     @api.multi
#     @api.onchange('product_id')
#     def product_id_change(self):
#         res = super(PriceListSaleOrderLine, self).product_id_change()
#
#         if self.product_id is False:
#             return res
#         else:
#
#             price_list = self.env['product.pricelist.item'].search(
#                 [('product_tmpl_id', '=', self.product_id.product_tmpl_id.id),('pricelist_id', '=', self.order_id.pricelist_id.id)])
#             total_text = ""
#             for line in price_list:
#                 text_show = " %i 個：每一個 %i 元 \n" % (line.min_quantity, line.fixed_price)
#                 total_text += text_show
#
#             self.price_list = total_text
#
#             if self.env.user.has_group('sales_team.group_sale_manager'):
#                 self.group_lock = False
#             else:
#                 self.group_lock = True
#
#             return res
#

